/*
Copyright SecureKey Technologies Inc. All Rights Reserved.

SPDX-License-Identifier: Apache-2.0
*/

package connector

import (
	esdispatcher "git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/ichain/events/service/dispatcher"
	"git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/providers/ichain"
)

type RegisterConnectionEvent struct {
	esdispatcher.RegisterEvent
	Reg *ConnectionReg
}

func NewRegisterConnectionEvent(eventch chan<- *ConnectionEvent, regch chan<- ichain.Registration, errch chan<- error) *RegisterConnectionEvent {
	return &RegisterConnectionEvent{
		Reg:           &ConnectionReg{Eventch: eventch},
		RegisterEvent: esdispatcher.NewRegisterEvent(regch, errch),
	}
}

type ConnectedEvent struct {
}

func NewConnectedEvent() *ConnectedEvent {
	return &ConnectedEvent{}
}

type DisconnectedError interface {
	error

	// IsFatal returns true if the error is fatal, meaning that a reconnect attempt would not succeed
	IsFatal() bool
}

type disconnectedError struct {
	cause error
	fatal bool
}

func (e *disconnectedError) Error() string {
	return e.cause.Error()
}

func (e *disconnectedError) IsFatal() bool {
	return e.fatal
}

type DisconnectedEvent struct {
	Err DisconnectedError
}

func NewDisconnectedEvent(cause error) *DisconnectedEvent {
	return &DisconnectedEvent{Err: &disconnectedError{cause: cause}}
}

func NewFatalDisconnectedEvent(cause error) *DisconnectedEvent {
	return &DisconnectedEvent{Err: &disconnectedError{cause: cause, fatal: true}}
}

type ConnectEvent struct {
	ErrCh        chan<- error
	FromBlockNum uint64
}

func NewConnectEvent(errch chan<- error) *ConnectEvent {
	return &ConnectEvent{ErrCh: errch}
}

type DisconnectEvent struct {
	Errch chan<- error
}

func NewDisconnectEvent(errch chan<- error) *DisconnectEvent {
	return &DisconnectEvent{Errch: errch}
}

type ConnectionEvent struct {
	Connected bool
	Err       DisconnectedError
}

func NewConnectionEvent(connected bool, err DisconnectedError) *ConnectionEvent {
	return &ConnectionEvent{Connected: connected, Err: err}
}
